<template>
  <div class="participant-info-container">
    <div class="info-panel">
      <div class="panel-header">
        <div class="panel-title">
          <el-icon><User /></el-icon>
          <span>参保人员信息管理</span>
        </div>
        <el-button type="primary" @click="handleAddParticipant">
          <el-icon><Plus /></el-icon>
          新增参保人员
        </el-button>
      </div>
      
      <div class="search-section">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="姓名">
            <el-input v-model="searchForm.name" placeholder="参保人员姓名" clearable />
          </el-form-item>
          <el-form-item label="身份证号">
            <el-input v-model="searchForm.idCard" placeholder="身份证号码" clearable />
          </el-form-item>
          <el-form-item label="参保状态">
            <el-select v-model="searchForm.status" placeholder="参保状态" clearable>
              <el-option label="正常" value="normal" />
              <el-option label="停保" value="stopped" />
              <el-option label="待审核" value="pending" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetSearchForm">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-table
        :data="filteredParticipants"
        stripe
        border
        style="width: 100%"
        highlight-current-row
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="姓名" width="100" align="center" />
        <el-table-column prop="gender" label="性别" width="60" align="center" />
        <el-table-column prop="idCard" label="身份证号" width="180" align="center" />
        <el-table-column prop="insuranceType" label="参保类型" width="100" align="center" />
        <el-table-column prop="insuranceNo" label="医保卡号" width="120" align="center" />
        <el-table-column prop="status" label="参保状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="参保日期" width="120" align="center" />
        <el-table-column prop="endDate" label="到期日期" width="120" align="center" />
        <el-table-column prop="address" label="家庭住址" min-width="150" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click.stop="handleEdit(scope.row)"
              plain
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="success"
              @click.stop="handleRenew(scope.row)"
              plain
              :disabled="scope.row.status !== 'expired'"
            >
              续保
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click.stop="handleStop(scope.row)"
              plain
              :disabled="scope.row.status !== 'normal'"
            >
              停保
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalParticipants"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 新增/编辑参保人员对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增参保人员' : '编辑参保人员信息'"
      width="50%"
    >
      <el-form :model="participantForm" label-width="100px" :rules="formRules" ref="participantFormRef">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="participantForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="participantForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="participantForm.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="参保类型" prop="insuranceType">
          <el-select v-model="participantForm.insuranceType" placeholder="请选择参保类型">
            <el-option label="城镇职工医保" value="employee" />
            <el-option label="城乡居民医保" value="resident" />
            <el-option label="公务员医保" value="civil" />
          </el-select>
        </el-form-item>
        <el-form-item label="医保卡号" prop="insuranceNo">
          <el-input v-model="participantForm.insuranceNo" placeholder="请输入医保卡号" />
        </el-form-item>
        <el-form-item label="参保日期" prop="startDate">
          <el-date-picker v-model="participantForm.startDate" type="date" placeholder="选择参保日期" />
        </el-form-item>
        <el-form-item label="到期日期" prop="endDate">
          <el-date-picker v-model="participantForm.endDate" type="date" placeholder="选择到期日期" />
        </el-form-item>
        <el-form-item label="家庭住址" prop="address">
          <el-input v-model="participantForm.address" placeholder="请输入家庭住址" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="participantForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="participantForm.remark" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue';
import { User, Search, Plus, Refresh } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const searchForm = reactive({
  name: '',
  idCard: '',
  status: ''
});

const currentPage = ref(1);
const pageSize = ref(10);
const dialogVisible = ref(false);
const dialogType = ref('add'); // 'add' 或 'edit'
const participantFormRef = ref(null);

// 表单校验规则
const formRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  insuranceType: [{ required: true, message: '请选择参保类型', trigger: 'change' }],
  insuranceNo: [{ required: true, message: '请输入医保卡号', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择参保日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择到期日期', trigger: 'change' }],
  address: [{ required: true, message: '请输入家庭住址', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ]
};

// 参保人员表单数据
const participantForm = reactive({
  id: null,
  name: '',
  gender: '男',
  idCard: '',
  insuranceType: '',
  insuranceNo: '',
  status: 'normal',
  startDate: '',
  endDate: '',
  address: '',
  phone: '',
  remark: ''
});

// 模拟参保人员数据
const participants = ref([
  {
    id: 1,
    name: '夏浩兴',
    gender: '男',
    idCard: '123123200007011234',
    insuranceType: '城镇职工医保',
    insuranceNo: 'YB10001',
    status: 'normal',
    startDate: '2022-01-01',
    endDate: '2022-12-31',
    address: '沈阳市和平区',
    phone: '13812345678',
    remark: ''
  },
  {
    id: 2,
    name: '李宝辰',
    gender: '男',
    idCard: '123123200007011234',
    insuranceType: '城乡居民医保',
    insuranceNo: 'YB10002',
    status: 'expired',
    startDate: '2021-01-01',
    endDate: '2021-12-31',
    address: '河北省秦皇岛市',
    phone: '13987654321',
    remark: ''
  },
  {
    id: 3,
    name: '郝强国',
    gender: '男',
    idCard: '123123200007011234',
    insuranceType: '公务员医保',
    insuranceNo: 'YB10003',
    status: 'normal',
    startDate: '2022-01-01',
    endDate: '2022-12-31',
    address: '辽宁省大连市',
    phone: '13765432198',
    remark: ''
  }
]);

// 过滤后的参保人员数据
const filteredParticipants = computed(() => {
  return participants.value.filter(p => {
    const nameMatch = !searchForm.name || p.name.includes(searchForm.name);
    const idCardMatch = !searchForm.idCard || p.idCard.includes(searchForm.idCard);
    const statusMatch = !searchForm.status || p.status === searchForm.status;
    return nameMatch && idCardMatch && statusMatch;
  });
});

// 总参保人员数量
const totalParticipants = computed(() => {
  return filteredParticipants.value.length;
});

// 获取参保状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'normal': return 'success';
    case 'expired': return 'warning';
    case 'stopped': return 'danger';
    case 'pending': return 'info';
    default: return '';
  }
};

// 获取参保状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'normal': return '正常';
    case 'expired': return '已过期';
    case 'stopped': return '已停保';
    case 'pending': return '待审核';
    default: return '未知';
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  ElMessage.success('查询成功');
};

// 重置搜索表单
const resetSearchForm = () => {
  searchForm.name = '';
  searchForm.idCard = '';
  searchForm.status = '';
  ElMessage.info('已重置查询条件');
};

// 处理新增参保人员
const handleAddParticipant = () => {
  dialogType.value = 'add';
  Object.keys(participantForm).forEach(key => {
    if (key !== 'gender' && key !== 'status') {
      participantForm[key] = '';
    }
  });
  participantForm.id = null;
  participantForm.gender = '男';
  participantForm.status = 'normal';
  dialogVisible.value = true;
};

// 处理编辑参保人员
const handleEdit = (row) => {
  dialogType.value = 'edit';
  Object.keys(participantForm).forEach(key => {
    participantForm[key] = row[key];
  });
  dialogVisible.value = true;
};

// 处理续保
const handleRenew = (row) => {
  ElMessageBox.confirm(`确认为 ${row.name} 办理续保吗？`, '续保确认', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟续保操作
    const index = participants.value.findIndex(p => p.id === row.id);
    if (index !== -1) {
      const now = new Date();
      const startDate = now.toISOString().split('T')[0];
      const endDate = new Date(now.setFullYear(now.getFullYear() + 1)).toISOString().split('T')[0];
      participants.value[index].status = 'normal';
      participants.value[index].startDate = startDate;
      participants.value[index].endDate = endDate;
      ElMessage.success(`${row.name} 续保成功`);
    }
  }).catch(() => {
    // 取消操作
  });
};

// 处理停保
const handleStop = (row) => {
  ElMessageBox.confirm(`确认为 ${row.name} 办理停保吗？`, '停保确认', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟停保操作
    const index = participants.value.findIndex(p => p.id === row.id);
    if (index !== -1) {
      participants.value[index].status = 'stopped';
      ElMessage.success(`${row.name} 停保成功`);
    }
  }).catch(() => {
    // 取消操作
  });
};

// 提交表单
const submitForm = () => {
  participantFormRef.value.validate((valid) => {
    if (valid) {
      if (dialogType.value === 'add') {
        // 模拟新增操作
        const newId = participants.value.length > 0 ? Math.max(...participants.value.map(p => p.id)) + 1 : 1;
        const newParticipant = { ...participantForm, id: newId };
        participants.value.push(newParticipant);
        ElMessage.success('新增参保人员成功');
      } else {
        // 模拟编辑操作
        const index = participants.value.findIndex(p => p.id === participantForm.id);
        if (index !== -1) {
          participants.value[index] = { ...participantForm };
          ElMessage.success('编辑参保人员信息成功');
        }
      }
      dialogVisible.value = false;
    } else {
      ElMessage.error('请完善表单信息');
      return false;
    }
  });
};

// 处理每页显示数量变化
const handleSizeChange = (size) => {
  pageSize.value = size;
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
};
</script>

<style scoped>
.participant-info-container {
  padding: 20px;
}

.info-panel {
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.panel-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
}

.panel-title .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.search-section {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 